<template>
  <div id="pricePopover" class="product-popover-view">

    <el-popover ref="popover1" v-model:visible="visible" :disabled="disabled" :placement="position" :width="900"
      trigger="manual">
      <template #reference>
        <slot />
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" size="mini">
        <div style="display: flex;justify-content: space-between">
          <div>
            <el-form-item label="产品信息">
              <el-select v-model="form.productId" placeholder="产品信息" clearable @change="handleChange"
                style="width: 100%">
                <el-option v-for="item in productList" :key="item.productId" :label="getProductName(item)"
                  :value="item.productId" />
              </el-select>
            </el-form-item>
          </div>

          <div v-if="isPosition">
            <el-form-item label="规划地区">
              <el-cascader
                      clearable
                      :show-all-levels="false"
                      v-model="form.area"
                      style="width: 100%;"
                      :options="citys"
                      placeholder="请选择规划地区"
                      :props="{ checkStrictly : true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                      @change="areaChange"
              />
            </el-form-item>
          </div>

          <div>
            <el-form-item>
              <el-button class="border-btn" size="mini" @click="onCancel">取消
              </el-button>
              <el-button class="main-btn" size="mini" type="primary" @click="onConfirm">确定
              </el-button>
            </el-form-item>
          </div>

        </div>

        <el-form-item prop="planId">
          <el-table ref="singleTable" max-height="300px" header-cell-class-name="popover-table-header" border
            :data="form.tableData" highlight-current-row style="width: 100%" @current-change="handleCurrentChange"
            @row-click="handledbclick">
            <el-table-column align="center" width="50">
              <template #default="{row}">
                <el-radio v-model="form.planId" :label="row?.planDetail?.id" />
              </template>
            </el-table-column>

            <el-table-column label="通用名" prop="planDetail.productPopularName" show-overflow-tooltip />

            <el-table-column label="商品名" prop="planDetail.productName" show-overflow-tooltip />

            <el-table-column label="包装规格" prop="planDetail.packSpecs" show-overflow-tooltip />

            <el-table-column label="生产厂家" prop="planDetail.producer" show-overflow-tooltip />

            <el-table-column v-if="isPosition && planType == 2" label="规划招商地区" show-overflow-tooltip >
              <template #default="{row}">
                <span>
                  {{row.planDetail?.areaName ? row.planDetail?.cityName + "/" + row.planDetail?.areaName : row.planDetail?.cityName ? row.planDetail?.cityName : row.planDetail?.provinceName}}
                </span>
              </template>
            </el-table-column>

            <el-table-column v-if="isPosition && planType == 3" label="直销地区" show-overflow-tooltip >
              <template #default="{row}">
                <span>
                  {{ row.planDetail?.provinceName }}/{{
              row.planDetail?.cityName
              }}/{{ row.planDetail?.areaName }}/{{row.planDetail?.streetName}}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="开发期限" show-overflow-tooltip>
              <template #default="{row}">
                {{handleDate(row?.allocationAgent?.allocationAgentDetails)}}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

      </el-form>

    </el-popover>

  </div>
</template>
<script>
  import area from "../../../../utils/area";
import {
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  ref,
  watch,
  reactive,
  toRefs,
} from "vue";
import { dateFormat } from "@/utils/date";
export default defineComponent({
  name: "Index",
  props: {
    position: {
      type: String,
      default: "bottom-end",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    planType: {
      type: String,
      default: "4",
    },
    headId: {
      type: Number,
      default: undefined,
    },
    isPosition:{
      type:Boolean,
      default:false
    }
  },
  setup(props, { emit }) {
    const validateId = (rule, value, callback) => {
      if (value === undefined || data.form.tableData.length === 0) {
        callback(new Error("请选择营销任务"));
      } else {
        callback();
      }
    };

    const currentInstance = getCurrentInstance();
    const api = inject("api");
    var visible = ref(false);
    var column = ref(null);
    const singleTable = ref(null);
    const citys = area
    const data = reactive({
      form: {
        productId: undefined,
        planId: undefined,
        tableData: [],
        area:[]
      },
      productList: [],
      rules: {
        planId: [{ required: true, validator: validateId, trigger: "change" }],
      },
      formRef: null,
    });

    const handleProductList = () => {
      if (props.headId) {

        let a = {
          listType: "1",
          planType: props.planType,
          page: 1,
          pageSize: 100,
          status: "4",
          headId: props.headId,
        };
        api.businessAgreement.BUSINESSAGREEMENT_TASK_PRODUCT(a).then((res) => {
          if (res.code === 0) {
            data.productList = res.data.list || [];
          }
        });
      }
    };

    const handleChange = (val) => {
      console.log(val);
      console.log(visible.value);
      getData();
    };

    const areaChange = () => {
      console.log(data.form.area)
      getData();
    }

    const getData = () => {

      if (props.headId) {
        let a = {
          listType: "1",
          planType: props.planType,
          page: 1,
          pageSize: 100,
          status: "4",
          headId: props.headId,
          productId: data.form.productId,
        };
        if (data.form.area && data.form.area.length){
          if (data.form.area.length == 1){
            a.provinceCode = data.form.area[0]
          }else if (data.form.area.length == 2){
            a.cityCode = data.form.area[1]
          }else if (data.form.area.length == 3){
            a.areaCode = data.form.area[2]
          }
        }
        api.plan.PLAN_DETAIL_LIST(a).then((res) => {
          if (!res.code) {
            data.form.tableData = res.data.list || [];
          }
        });
      }
    };

    const handleDate = (row) => {
      if (row && row.length > 0) {
        row.sort((a, b) => {
          return (
            new Date(b.dealTime).getTime() - new Date(a.dealTime).getTime()
          );
        });
        return dateFormat("yyyy-mm-dd", row[0]?.dealTime);
      }
    };

    watch(
      () => props.headId,
      (newS, oldS) => {
        getData();
        handleProductList();
      }
    );

    const handleCurrentChange = (val) => {
      column.value = val;
    };

    const onConfirm = () => {
      data.formRef.validate((valid) => {
        if (valid) {
          const a = JSON.parse(JSON.stringify(column.value));
          emit("confirm", a);
          setTimeout(() => {
            column.value = null;
            visible.value = false;
          }, 100);
        }
      });
    };

    const onCancel = () => {
      singleTable.value.setCurrentRow();
      data.form.planId = undefined;
      column.value = null;
      visible.value = false;
      data.form = {
        productId: undefined,
        planId: undefined,
        tableData: [],
        area:[]
      };
    };

    const onClose = () => {
      singleTable.value.setCurrentRow();
      column.value = null;
      visible.value = false;
      data.form = {
        productId: undefined,
        planId: undefined,
        tableData: [],
        area:[]
      };
    };

    const handledbclick = (row, column, event) => {
      data.form.planId = row?.planDetail?.id;
      column.value = row;
      emit("confirm", column);
    };

    const openPopover = () => {
      getData();
      handleProductList();
      setTimeout(() => {
        visible.value = true;
      }, 300);
    };

    return {
      visible,
      singleTable,
      column,
      citys,
      ...toRefs(data),
      handleCurrentChange,
      onConfirm,
      onCancel,
      onClose,
      handledbclick,
      openPopover,

      handleProductList,
      handleDate,
      handleChange,
      areaChange,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/style/basics.scss";

:deep(.el-radio__label) {
  display: none;
}
</style>
